package Base;

import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Iterator;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.testng.*;
import org.testng.log4testng.Logger;

/**
 * Created by Alain on 2016/3/8.
 */
@SuppressWarnings("unused")
public class TestBase {
    private String localEnvironment = "http://bim.wanda.cn";
    private int responseCode = 500;
    public  String responseBody = null;
    protected static Logger log = Logger.getLogger(TestBase.class);

    //request without body
    public String apiResponse(String path, String method) throws IOException {
        if (method.equals("POST") || method.equals("GET") || method.equals("PUT") || method.equals("DELETE")){
            try {
                URL connectionURL = new URL(localEnvironment + path);
                log.info("Request method is: " + method);
                log.info("Request URL is: " + connectionURL.toString());
                HttpURLConnection httpURLConnection = (HttpURLConnection) connectionURL.openConnection();
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                httpURLConnection.setRequestMethod(method);
                httpURLConnection.setUseCaches(false);
                httpURLConnection.connect();

                responseCode = httpURLConnection.getResponseCode();
                String sCurrentLine;
                String sTotalString = null;
                if (responseCode == 200){
                    InputStream is = httpURLConnection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
                    while ((sCurrentLine = reader.readLine()) != null){
                        if (sCurrentLine.length() > 0){
                            sTotalString = sTotalString + sCurrentLine.trim();
                        }
                    }
                    responseBody = sTotalString.substring(4);
                }else{
                    InputStream is = httpURLConnection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
                    while ((sCurrentLine = reader.readLine()) != null){
                        if (sCurrentLine.length() > 0){
                            sTotalString = sTotalString + sCurrentLine.trim();
                        }
                    }
                    responseBody = sTotalString.substring(4);
                    Assert.fail("Response code is: " + responseCode + "\nResponse body is: " + responseBody);
                }

                httpURLConnection.disconnect();
            }catch (SecurityException e){
                Assert.fail(e.toString());
            }catch (ProtocolException e){
                Assert.fail(e.toString());
            }
        }else {
            Assert.fail("No support for this method:" + method);
        }
        log.info("Response is: " + responseBody);
        return responseBody;
    }
    
    //request with String
    public String apiResponse(String path, String method, String requestBody) throws IOException {
        if (method.equals("POST")){
            try {
                URL connectionURL = new URL(localEnvironment + path);
                log.info("Request method is: " + method);
                log.info("Request URL is: " + connectionURL.toString());
                HttpURLConnection httpURLConnection = (HttpURLConnection) connectionURL.openConnection();
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                httpURLConnection.setRequestMethod(method);
                httpURLConnection.setRequestProperty("Content-type", "application/json");
                httpURLConnection.setUseCaches(false);

                OutputStream os = httpURLConnection.getOutputStream();
                os.write(requestBody.getBytes());
                os.flush();
                os.close();

                responseCode = httpURLConnection.getResponseCode();
                String sCurrentLine;
                String sTotalString = null;
                if (responseCode == 200){
                    InputStream is = httpURLConnection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
                    while ((sCurrentLine = reader.readLine()) != null){
                        if (sCurrentLine.length() > 0){
                            sTotalString = sTotalString + sCurrentLine.trim();
                        }
                    }
                    responseBody = sTotalString.substring(4);
                }else{
                    InputStream is = httpURLConnection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
                    while ((sCurrentLine = reader.readLine()) != null){
                        if (sCurrentLine.length() > 0){
                            sTotalString = sTotalString + sCurrentLine.trim();
                        }
                    }
                    responseBody = sTotalString.substring(4);
                    Assert.fail("Response code is: " + responseCode + "\nResponse body is: " + responseBody);
                }

                httpURLConnection.disconnect();
            }catch (SecurityException e){
                Assert.fail(e.toString());
            }catch (ProtocolException e){
                Assert.fail(e.toString());
            }
        } else{
            Assert.fail("No support for this method:" + method);
        }
        log.info("Response is: " + responseBody);
        return responseBody;
    }

    //request with FileInputStream
    public String apiResponse(String path, String method, FileInputStream FIS) throws IOException {
        if (method.equals("POST")){
            try {
                URL connectionURL = new URL(localEnvironment + path);
                log.info("Request method is: " + method);
                log.info("Request URL is: " + connectionURL.toString());
                HttpURLConnection httpURLConnection = (HttpURLConnection) connectionURL.openConnection();
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                httpURLConnection.setRequestMethod(method);
                httpURLConnection.setRequestProperty("Content-type", "application/octet-stream");
                httpURLConnection.setUseCaches(false);

                OutputStream os = httpURLConnection.getOutputStream();
                os.write(FIS.toString().getBytes());
                os.flush();
                os.close();

                responseCode = httpURLConnection.getResponseCode();
                String sCurrentLine;
                String sTotalString = null;
                if (responseCode == 200){
                    InputStream is = httpURLConnection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
                    while ((sCurrentLine = reader.readLine()) != null){
                        if (sCurrentLine.length() > 0){
                            sTotalString = sTotalString + sCurrentLine.trim();
                        }
                    }
                    responseBody = sTotalString.substring(4);
                }else{
                    InputStream is = httpURLConnection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
                    while ((sCurrentLine = reader.readLine()) != null){
                        if (sCurrentLine.length() > 0){
                            sTotalString = sTotalString + sCurrentLine.trim();
                        }
                    }
                    responseBody = sTotalString.substring(4);
                    Assert.fail("Response code is: " + responseCode + "\nResponse body is: " + responseBody);
                }

                httpURLConnection.disconnect();
            }catch (SecurityException e){
                Assert.fail(e.toString());
            }catch (ProtocolException e){
                Assert.fail(e.toString());
            }
        } else{
            Assert.fail("No support for this method:" + method);
        }
        log.info("Response is: " + responseBody);
        return responseBody;
    }

    //construct request url
    public String getURL(String url){
        if ( !url.substring(url.length()-1).equals("?"))
            url = url + "&";
        return url;
    }

    //return data
    public void checkResponseValue(String key[]){
        JSONObject data = JSON.parseObject(responseBody, JSONObject.class);

        if (data.containsKey("data") && StringUtils.isNotEmpty(data.getString("data"))) {
            String responseData = data.getString("data");

            if (StringUtils.equals(String.valueOf(responseData.charAt(0)), "{")){
                JSONObject responseObject = JSONObject.parseObject(responseData);

                for (int i=0; i<key.length; i++){
                    if (StringUtils.isNotEmpty(responseObject.getString(key[i]))) {
                        log.info(key[i] + " is " + responseObject.getString(key[i]));
                    } else {
                        log.info(key[i] + " DOESN'T exist!");
                    }
                }

            }else if (StringUtils.equals(String.valueOf(responseData.charAt(0)), "[")){
                JSONArray responseArray = data.getJSONArray("data");

                if (responseArray.size() <= 0) {
                    log.info("Response data array is empty!");
                }else{
                    for (int i=1; i<=responseArray.size(); i++) {
                        for (int keyItem=0; keyItem<key.length; keyItem++){
                            JSONObject temp = responseArray.getJSONObject(i-1);

                            if (StringUtils.isNotEmpty(temp.getString(key[keyItem]))) {
                                log.info("the "+i+ " item's " + key[keyItem] + " is " + temp.getString(key[keyItem]));
                            }else{
                                log.info("the "+i+ " item's " + key[keyItem] + " DOESN'T exist!");
                            }
                        }
                    }
                }

            }else{
                Assert.fail("JSON format ISN'T correct!");
            }

        }else{
            Assert.fail("No data response");
        }
    }
}
